
//表格内容区
import { useState, useEffect, useMemo, useCallback } from 'react';
import { Typography, Popconfirm, Popover, Image, message } from 'antd';
import { isEmpty } from 'lodash';
import CommonLoading from '@/components/CommonLoading';
import CommonTag from '@/components/CommonTag';
import IconFont from '@/components/IconFont';
import { formatZjfImg, formatHref, formatZjfHref, formatAmount } from '@/utils/utils.jsx';
import { platformType } from '@/utils/config';
import ApplyReturnModal from './ApplyReturnModal';
import ApplyReturnNextModal from './ApplayReturnNextModal'; 
import { getRefundApplyDetailsOp, applyAgainOp, cancelRefundApplyOp, zhifaCancelRefundApplyOp } from '../../../service'

import styles from './index.module.less';

const { Paragraph } = Typography;

const afterSalesTypeMap = {
  0: '退货退款',
  1: '仅退款',
  2: '仅退款',
  3: '换货',
  6: '价保',
  7: '补寄',
}

const refundStateMap = {
  10: '待登记',
  20: '部分登记',
  30: '处理中',
  40: '处理完成',
  50: '已取消',
  0: '待商家处理',
  1: '商家已拒绝',
  2: '待买家退货',
  3: '待商家收货',
  4: '退款成功',
  5: '退款关闭',
  6: '待商家寄出',
  7: '待买家收货换货成功',
  8: '换货失败',
}

//标签映射  goodsLabel	商品标签[1:拿货，2:库存，3:直发]
const TagMap = {
  1: 'nahuo',
  2: 'zifa',
  3: 'cjzf',
  4: 'dangkou'
}

export default ({ data, expressList, handleJumptDetail, handleUpdateTable }) => {

  const [loading, setLoading] = useState(false);
  const [item, setItem] = useState([]);
  const [visible, setVisible] = useState(false);

  const { id, channelId, refundOrderGoodsList = [], logisticsNo, logisticsCompany, afterSalesType, afterSalesTypeName, processingTimeRemain, orderChannel, channelName, refundState, refundStateName, refundReason, refundVoucher, logisticsFee, refundAmountTotal, realLogisticsFee, refundMeth } = data

  //商品信息渲染
  const renderGoodsContent = useMemo(() => {
    return refundOrderGoodsList.map(item => {
      const { storeId, goodsImage, storeName, goodsName, refundAmount, goodsSpec, goodsId, spuId, goodsLabel, isComposeGoods, applyRefundNum, successRefundNum } = item
      const imgSrc = formatZjfImg(goodsImage, storeId, 0, 64);
      let detailSrc = null;
      if (orderChannel) {
        if (orderChannel == -1) {
          detailSrc = formatZjfHref(goodsId);//商城
        } else {
          detailSrc = formatHref(spuId, orderChannel, goodsId);//三方
        }
      }
      return (
        <div className={styles.goodsBlock} key={goodsId}>
          <Popover content={<div className='custom-ant-popver-content'><img src={imgSrc} alt=" " style={{ width: '200px' }} /></div>}>
            <img src={imgSrc} alt=" " className='tableGoodsImg' />
          </Popover>
          <div className='goodsTextBox'>
            <a href={detailSrc} target='_blank'>
              <Popover content={<div className='custom-ant-popver-content'>【{storeName}】{goodsName} {goodsSpec}</div>}>
                <div className='textOverflowMultiTwo common-color1' style={{ wordBreak: 'break-all' }}>【{storeName}】{goodsName}</div>
                <div className='textOverflowMultiOne'><span className='commom-color4'>{goodsSpec}</span></div>
              </Popover>
            </a>
            <div className='textOverflowMultiOne'>商品编号：{goodsId}</div>
            <CommonTag type={TagMap[goodsLabel]} />
            {isComposeGoods == 2 && <CommonTag type='zuhe' />}
          </div>
          <div className='applyNumber common-color9'>{applyRefundNum}&nbsp;/&nbsp;{successRefundNum}</div>
          <div className='accountMoney'>
            <span className='common-color9'>退款：￥{formatAmount(refundAmount)}</span>
          </div>
        </div>
      )
    })
  }, [refundOrderGoodsList])

  //渲染退货凭证
  const renderRefundRroof = useMemo(() => {
    if (refundVoucher) {
      const imgArr = JSON.parse(refundVoucher);
      return (
        <div className={styles.imgFlex}>
          {imgArr.map(item => {
            return <Image src={item} className={styles.imgStyle} key={item} />
          })}
        </div>
      )
    } else {
      return ''
    }
  }, [refundVoucher])

  //渲染所属店铺
  const renderBelongStore = () => {
    const { orderChannel, ecStoreName, outOrderSn, extend1 } = data
    try {
      return (
        <>
          {platformType[orderChannel] && <IconFont type={`icon${platformType[orderChannel]}`} style={{ fontSize: 24, marginRight: 2 }} />}
          <p className="common-color3" style={{ fontWeight: 'bold' }}>{ecStoreName}</p>
          {outOrderSn && JSON.parse(outOrderSn).map((item, index) => {
            return <p key={index} style={{ wordBreak: 'break-all' }}>{item}</p>
          })}
          {extend1 && <CommonTag type='yichangdanger' />}
        </>
      )
    } catch {
      return (
        <>
          {platformType[orderChannel] && <IconFont type={`icon${platformType[orderChannel]}`} style={{ fontSize: 24, marginRight: 2 }} />}
          <p className="common-color3" style={{ fontWeight: 'bold' }}>{ecStoreName}</p>
          <p style={{ wordBreak: 'break-all' }}>{outOrderSn}</p>
          {extend1 && <CommonTag type='yichangdanger' />}
        </>
      )
    }
  }

  //渲染操作列
  const renderOperatorColumn = useMemo(() => {
    const { id, channelId, refundState, refundOrderSn } = data
    if (channelId) {//代发
      if (refundState == '10') {//待登记
        return (<span className="opera-span-common"><span onClick={() => handleEditApply(id)}>编辑</span>
          <i>|</i>
          <Popconfirm
            title="是否确定取消退货申请单？"
            onConfirm={() => cancelRefundApply(id)}
            okText="确定"
            cancelText="取消"
          >
            <span>取消申请</span>
          </Popconfirm>
        </span>)
      } else if (refundState == '50') {//已取消
        return null
      } else {
        return <span className="opera-span-common"><span onClick={() => handleJumptDetail(refundOrderSn)}>退货商品明细</span></span>;
      }
    } else {
      const isRefused1 = refundState == '1' && (afterSalesType == 1 || afterSalesType == 2),//仅退款的商品已拒绝
      isRefused2 = refundState == '1' && !afterSalesType; //退货退款类型的商家已拒绝
      return (<span className="opera-span-common">
        {isRefused1 && <Popconfirm
          title="是否确认重新申请退款？"
          onConfirm={() => zhifaApplyAgainOperator()}
          okText="确定"
          cancelText="取消"
        >
          <span>重新申请</span>
        </Popconfirm>}
        {isRefused2 && <span onClick={()=>handleEditApply(id, true)}>重新申请</span>}
        {(isRefused1 || isRefused2) && (refundState == '1' || refundState == '3') && <i>|</i>}
        {/* 待商家收货 */}
        {refundState == '3' && <><span onClick={()=>handleEditApply(id)}>编辑</span><i>|</i></>}
        {/* 商家已拒绝           待商家收货 */}
        {(refundState == '1' || refundState == '3') && !afterSalesType && <Popconfirm
          title="是否确定取消退货申请单？"
          onConfirm={() => cancelRefundApply(id, true)}
          okText="确定"
          cancelText="取消"
        >
          <span>取消申请</span>
        </Popconfirm>}
      </span>)
    }
  }, [data])

  //获取编辑商品
  const handleEditApply = async (refundOrderId, isZhifa) => {
    setLoading(true);
    const { data, success } = await getRefundApplyDetailsOp({ refundOrderId })
    if (success) {
      setItem(data);
      setVisible(isZhifa ? 2 : 1);
    } else {
      setItem({});
    }
    setLoading(false);
  }

  //重新申请操作
  const zhifaApplyAgainOperator = async (val) => {
    setLoading(true);
    const params = val || {refundOrderIds:[id]};
    const { success } = await applyAgainOp({...params, isBatch:2});
    if (success) {
      message.success('重新申请成功！');
      setVisible(false);
      handleUpdateTable();
    }
    setLoading(false);
  }

  //取消
  const cancelRefundApply = async (refundOrderId, isZhifa) => {
    setLoading(true);
    let res;
    if(isZhifa){
      res = await zhifaCancelRefundApplyOp({ refundOrderId });//直发单
    }else{
      res = await cancelRefundApplyOp({ refundOrderId });//代发单
    }
    if (res?.success) {
      handleUpdateTable();
    }
    setLoading(false);
  }

  const computeTimeLife = (value) => {
    let seconds = Math.round((new Date(value) - new Date().getTime()) / 1000);//单位：s
    const days = Math.floor(seconds / (24 * 60 * 60));
    seconds = seconds - (days * 24 * 60 * 60);
    const hours = Math.floor(seconds / (60 * 60));
    seconds = seconds - (hours * 60 * 60);
    const minutes = Math.floor(seconds / 60);
    seconds = seconds - minutes * 60;
    return { days, hours, minutes, seconds }
  }

  const renderTimeLift = useCallback((value) => {
    if(new Date(value).getTime() > Date.now()){
      const { days, hours, minutes } = computeTimeLife(value);
      return `还剩${days}天${hours}时${minutes}分`;
    }else{
      return null;
    }
  }, [])

   //退货申请单弹窗
   const ApplyReturnModalProps = {
    item,
    expressList,
    visible: visible == 1,
    handleOk() {
      setVisible(false);
      handleUpdateTable();
    },
    handleCancel() {
      setVisible(false);
    }
  }

  //退货退款被拒后重新申请弹窗
  const ApplyReturnProps = {
    item,
    expressList,
    visible: visible == 2,
    flag:true,
    handleOk(val) {
      zhifaApplyAgainOperator(val);
    },
    handleCancel() {
      setVisible(false);
    }
  }

  const renderGoodsSurfix = useMemo(()=>{
    if(channelId === 0){//直发
      if((afterSalesType == 1 || afterSalesType == 2) && refundState == 4){//仅退款、退款成功
        return (<div className={styles.surfixBox}>
          <p>商品实退：<span className='common-color9'>￥{formatAmount(refundAmountTotal)}{refundMeth == 3 && <span>&nbsp;&nbsp;注意线下退款</span>}</span></p>
          <p>运费实退：<span className='common-color9'>￥{formatAmount(realLogisticsFee || 0)}&nbsp;&nbsp;&nbsp;&nbsp;</span></p>
          <p style={{ float: 'right', marginRight: '16px' }}>运费：<span className='common-color9'>￥{formatAmount(logisticsFee)}</span></p>
        </div>)
      }else if(refundState == 4){//退款成功（非仅退款）
        return <p style={{textIndent:'28px'}}>商品实退：<span className='common-color9'>￥{formatAmount(refundAmountTotal)}{refundMeth == 3 && <span>&nbsp;&nbsp;注意线下退款</span>}</span></p>
      }else if(afterSalesType == 1 || afterSalesType == 2){// 仅退款（未退款成功）
        return <p  className={`${styles.surfixBox} ${styles.specSurfixBox}`}><span>运费：<span className='common-color9'>￥{formatAmount(logisticsFee)}</span></span></p>
      }
    }else{
      return null;
    }
  },[data])

  return (
    <>
      <div className={styles.tableHeader} key={id}>
        <div className={styles.firstGoodsColum}>
          {renderGoodsContent}
          {renderGoodsSurfix}
        </div>
        <div className={styles.expressInfo}>
          {logisticsNo && <Paragraph copyable style={{ marginBottom: 0 }}>{logisticsNo}</Paragraph>}{logisticsCompany}
        </div>
        <div className={styles.belongStore}>{renderBelongStore()}</div>
        {/* 售后类型 */}
        <div className={styles.afterSaleType}>
          {/* {afterSalesTypeMap[afterSalesType]} */}
          {afterSalesTypeName}
        </div>
        {/* 所属渠道 */}
        <div className={styles.belongChannel}>{channelId === 0 ? `${refundOrderGoodsList[0]?.storeName}(直发)` : channelName}</div>
        {/* 售后单状态 */}
        <div className={styles.refundState}>
          {/* {refundStateMap[refundState]} */}
          <p className={refundState == 1 ? 'common-color9' : ''}>{refundStateName}</p>
          {processingTimeRemain && refundState != 4 && refundState != 5  && refundState != 50 && <p className='common-color13'>{renderTimeLift(processingTimeRemain)}</p>}
        </div>
        <div className={styles.refundReason}> <Popover content={<div className='custom-ant-popver-content'>{refundReason}</div>}><span className="textOverflowMultiThree" style={{ wordBreak: 'break-all' }}>{refundReason}</span></Popover></div>
        <div className={styles.refundRroof}>{renderRefundRroof}</div>
        <div className={styles.opera}>{renderOperatorColumn}</div>
      </div>
      {visible == 1 && <ApplyReturnModal {...ApplyReturnModalProps} />}
      {visible == 2 && <ApplyReturnNextModal { ...ApplyReturnProps} /> }
      {loading && <CommonLoading loading={loading} />}
    </>
  )

}